<template>
	<div class="main bg">
		<showtitle showtitle="寄售"></showtitle>

		<ul class="TopNav">
			<li @click="changeSwiper(0)" :class="{ 'select animation1': activePage === 0 }">
				综合排序
			</li>
			<li @click="changeSwiper(1)" :class="{ 'select animation1': activePage === 1 }">
				价格较高
			</li>
			<li @click="changeSwiper(2)" :class="{ 'select animation1': activePage === 2 }">
				距离较近
			</li>
			<li @click="changeSwiper(3)" :class="{ 'select animation1': activePage === 3 }">
				最新发布
			</li>
		</ul>

		<div class="empty" v-if="this.$store.getters.getUser.name=='未登录'">
			<h1>您还没有登入~</h1>
			<h1>快去登录查看新世界</h1>
		</div>


		<swiper class="swiper-container" @slideChange="onSlideChange" ref="mySwiper" v-else>
			<swiper-slide class="swiper-slide">
				
				<div class="box_container card" @click="gointo(item.uid)" v-for="(item,index) in getShopsByHasGet">
					<img class="box_container_img" :src="item.head_img" />
					<div class="box_container_right">
						<div class="box_top">
							<label>{{item.user.name}}</label>
							<label>企业等级：{{item.user.level}}级</label>
						</div>
						<div class="box_bottom">
							<label>已回收：{{item.has_get}}kg</label>
							<div>进入查看>></div>
						</div>
					</div>
				</div>
			</swiper-slide>
			<swiper-slide>
				<baidu-map @ready="getCurrentCity" style="display:none">

				</baidu-map>
				<div class="box_container card" @click="gointo(item.uid)" v-for="(item,index) in pricesList">
					<img class="box_container_img" :src="item.head_img" />
					<div class="box_container_right">
						<div class="box_top">
							<label>{{item.user.name}}</label>
							<label>{{formatDate(item.timestamp)}}</label>
						</div>
						<div class="box_bottom">
							<label>平均价格：{{item.averagePrice.toFixed(2)}}kg</label>
							<div>进入查看>></div>
						</div>
					</div>
				</div>
			</swiper-slide>
			<swiper-slide>
				<div class="box_container card" @click="gointo(item.uid)" v-for="(item,index) in distanceList">
					<img class="box_container_img" :src="item.head_img" />
					<div class="box_container_right">
						<div class="box_top">
							<label>{{item.user.name}}</label>
							<label>{{formatDate(item.timestamp)}}</label>
						</div>
						<div class="box_bottom">
							<label>距您最近：{{item.nearestStation.distance.toFixed(2)}}km</label>
							<div>进入查看>></div>
						</div>
					</div>
				</div>
			</swiper-slide>
			<swiper-slide>
				<div class="box_container card" @click="gointo(item.uid)" v-for="(item,index) in getShopsByTime">
					<img class="box_container_img" :src="item.head_img" />
					<div class="box_container_right">
						<div class="box_top">
							<label>{{item.user.name}}</label>
							<label>{{formatDate(item.timestamp)}}</label>
						</div>
						<div class="box_bottom">
							<label>已回收：{{item.has_get}}kg</label>
							<div>进入查看>></div>
						</div>
					</div>
				</div>
			</swiper-slide>
		</swiper>





	</div>
</template>

<script>
	import BaiduMap from 'vue-baidu-map/components/map/Map.vue';
	export default {
		name: "mails",
		data() {
			return {
				shops: [],
				activePage: 0,
				pricesList: [],
				point: {},
				distanceList: [],
			};
		},
		components: {
			BaiduMap,
		},
		mounted() {
			this.getDataList();
		},
		beforeDestroy() {
			
			if(this.$refs.mySwiper != null && this.$refs.mySwiper.swiperInstance != null){
				// 在组件销毁前卸载Swiper
				this.$refs.mySwiper.swiperInstance.destroy(true,
					true); // 第二个参数为true会重置swiper到初始状态，第三个参数为true会移除swiper内部的dom元素  
			}
			

		},
		computed: {
			getShopsByTime() {
				const shopsCopy = this.shops.slice();
				return shopsCopy.sort((a, b) => b.timestamp - a.timestamp);
			},
			getShopsByHasGet() {
				const shopsCopy = this.shops.slice();
				return shopsCopy.sort((a, b) => b.has_get - a.has_get);
			},
		},
		methods: {
			getCurrentCity({
				BMap
			}) {
				let geolocation = new BMap.Geolocation();
				geolocation.getCurrentPosition((result) => {
					this.point = result.point;
					console.log(this.point);
					this.getShopsByDistance();

				})
			},
			getShopsByPrice() {

				// 创建原数组的浅拷贝  
				const shopsCopy = this.shops.slice();
				// 计算平均价格并保留所有原始属性，包括新增的 head_img  
				const itemsWithAveragePrice = shopsCopy.map(item => {
					// 将字符串价格转换为数字并计算平均值  
					const prices = item.buys.map(buy => parseFloat(buy.price));
					const averagePrice = prices.reduce((sum, price) => sum + price, 0) / prices.length;
					// 返回包含所有原始属性和新计算出的 averagePrice 的对象  
					return {
						...item, // 这会包含 head_img 和其他所有原始属性  
						averagePrice,
					};
				});

				this.pricesList = itemsWithAveragePrice.sort((a, b) => b.averagePrice - a.averagePrice);

			},
			calculateDistance(point1, point2) {
				if (!point1 || !point2 || !point1.lat || !point1.lng || !point2.lat || !point2.lng) {
					throw new Error('Invalid points provided to calculateDistance');
				}
				const rad = Math.PI / 180;
				const lat1 = point1.lat * rad;
				const lat2 = point2.lat * rad;
				const deltaLng = (point1.lng - point2.lng) * rad;
				const R = 6371; // 地球半径，单位为千米  
				const distance = Math.acos(Math.sin(lat1) * Math.sin(lat2) +
					Math.cos(lat1) * Math.cos(lat2) * Math.cos(deltaLng)) * R;
				return distance;
			},

			getShopsByDistance() {
				const companiesWithNearestStations = this.shops.map(company => {
					// 检查 stations 是否为有效的非空数组  
					if (!Array.isArray(company.stations) || company.stations.length === 0) {
						console.error('Invalid stations array for company:', company);
						// 可以选择跳过当前公司或返回一个包含错误信息的对象  
						return {
							...company,
							nearestStation: null,
							error: 'No stations provided'
						};
					}

					const stationsWithDistance = company.stations.map(station => {
						if (!station || !station.lat || !station.lng) {
							console.error('Invalid station object:', station);
							// 可以选择跳过当前站点或返回一个包含错误信息的对象  
							return null;
						}
						const distance = this.calculateDistance(this.point, station);
						return {
							...station,
							distance
						};
					}).filter(station => station !== null); // 过滤掉无效的站点  

					// 对剩余的有效站点进行排序，并取最近的站点  
					const nearestStation = stationsWithDistance.length > 0 ? stationsWithDistance.sort((a, b) => a
						.distance - b.distance)[0] : null;
					return {
						...company,
						nearestStation
					};
				});

				// 根据最近站点的距离对所有公司进行排序  
				this.distanceList = companiesWithNearestStations
					.filter(company => company.nearestStation !== null) // 过滤掉没有最近站点的公司  
					.sort((a, b) => a.nearestStation.distance - b.nearestStation.distance);
			},

			formatDate(timestamp) {
				const date = new Date(timestamp); // JavaScript时间戳是以毫秒为单位的，所以需要乘以1000  
				const year = date.getFullYear();
				const month = this.padZero(date.getMonth() + 1); // getMonth()返回的月份是从0开始的，所以需要加1  
				const day = this.padZero(date.getDate());
				const hour = this.padZero(date.getHours());
				const minutes = this.padZero(date.getMinutes());
				return `${year}-${month}-${day}`;
			},
			padZero(num) {
				return num < 10 ? '0' + num : num;
			},
			getSrc() {
				this.shops.forEach((e) => {
					let url = `${this.IP}/shop_head/${e.user.uid}.jpg`
					this.axios.head(url).then(res => {
						if (res.status == 200) {
							e.head_img = url
						}
						this.$forceUpdate();
						this.getShopsByPrice();
						
					}).catch(error => {
						// 处理错误  
						e.head_img = `${this.IP}/shop_head/normal.jpg`
					});;;
				})
				console.log(this.shops);
			},
			onSlideChange() {
				this.activePage = this.$refs.mySwiper.swiperInstance.activeIndex;
				console.log(this.activePage);
			},
			changeSwiper(e) {
				this.$refs.mySwiper.swiperInstance.activeIndex = e;
				this.activePage = e;
			},
			gointo(uid) {
				this.$router.push('/detail?shopid=' + uid);
			},
			openSearch() {
				this.$router.push('/searchpage2');
			},
			getDataList() {
				this.axios.get(`${this.IP}/get_shops`, {
					params: {

					}
				}).then(res => {
					console.log(res.data);
					this.shops = res.data.filter(shop => shop.stations != null && shop.stations.length !== 0 && shop.buys !== null && shop.buys.length !== 0 && shop.buys.length != '[]');
					this.getSrc();
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;
			}

		}

	}
</script>

<style scoped>
	.empty{
		width: 50vw;
		text-align: center;
		margin: 0 auto;
		margin-top: 10vh;
		color: gray;
	}
	.animation1{
		animation: 0.6s swing alternate-reverse;
	}
	.search-box {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 95%;
		height: 10vw;
		background-color: white;
		color: #dbdbdb;
		margin: 0 auto;
		margin-bottom: 1vw;
	}

	.search-box img {
		width: 6vw;
		height: 6vw;
	}

	.search-box-text {
		height: 8vw;
		line-height: 8vw;
		text-align: center;
		font-size: 5vw;
		letter-spacing: .5vw;
		margin-left: 1.5vw;
	}

	.swiper-container {
		min-height: 100vh;
		height: auto;
	}

	.box_container {
		display: flex;
		flex-direction: row;
		margin: 1vh;
		border-radius: 5vw;
	}

	.box_container_img {
		width: 10vh;
		padding: 1vh;
		border: 1px solid #f3f3f3;
		border-radius: 5vw;
	}

	.box_container_right {
		flex: 1;
		padding: 4vw;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.box_top,
	.box_bottom {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.TopNav {
		display: flex;
		justify-content: space-around;
		align-items: center;
		border: 1px solid #ebebeb;
		background-color: #f3f3f3;
		margin: 0 auto;
		width: 99vw;
	}

	.TopNav li {
		display: flex;
		flex-direction: column;
		position: relative;
		padding: 3vw;
		color: #333;
	}

	.TopNav li.select {
		border-bottom: 2px solid #fc9b39;
		font-weight: bold;
	}

	.banner img {
		width: 100vw;
		max-width: 100vw;
		height: 24vh;
		background-size: cover;
	}

	.box_bottom div {
		background: linear-gradient(to right, #ffcf0e, #ff8002);
		border-radius: 1em;
		text-align: center;
		padding: 1vw 2vw 1vw 2vw;
		color: white;
		font-weight: bold;
	}
</style>